import Foundation

struct WIFIStoreTools {
    
    private let wifiInfoKey = "casdon_wifiInfo"
    static let shared = WIFIStoreTools()
    private init() {
        
        KeychainManager.erase(key: wifiInfoKey)
    }

    // MARK: - 数据结构
    struct WifiInfo: Codable {
        let ssid: String
        let password: String
    }

    // MARK: - 保存单个 Wi-Fi 信息（自动去重）
    func saveWifiInfo(_ info: WifiInfo) -> Bool {
        var savedInfos = loadWifiInfos()
        if savedInfos.count == 0 {
            savedInfos.insert(info, at: 0)
            return saveWifiInfos(infoArray: savedInfos)
        }
        // 如果已存在相同 SSID，则更新密码；否则新增
        if let index = savedInfos.firstIndex(where: { $0.ssid == info.ssid }) {
            savedInfos[index] = info
            
        } else {
            savedInfos.append(info)
        }
        return  updateWifiInfos(infoArray: savedInfos)
    }
    
    // MARK: - 查询指定 SSID 的密码
    func getWifiInfo(ssid: String) -> WifiInfo? {
        return loadWifiInfos().first { $0.ssid == ssid }
    }
    
    // MARK: - 私有方法：保存 Wi-Fi 数组到 Keychain
    private func saveWifiInfos(infoArray: [WifiInfo]) -> Bool {
        do {
            let data = try JSONEncoder().encode(infoArray)
            if let rawString = String(data: data, encoding: .utf8) {
                print("Keychain 存储的原始数据：\(rawString)")
            }
            return KeychainManager.save(value: data, key: wifiInfoKey)
        } catch {
            print("编码失败: \(error)")
            return false
        }
    }
    
    private func updateWifiInfos(infoArray: [WifiInfo]) -> Bool {
        do {
            let data = try JSONEncoder().encode(infoArray)
            if let rawString = String(data: data, encoding: .utf8) {
                print("Keychain 存储的原始数据：\(rawString)")
            }
            return KeychainManager.update(value: data, forKey: wifiInfoKey)
        } catch {
            print("编码失败: \(error)")
            return false
        }
    }
    
    
    // MARK: - 从 Keychain 加载所有 Wi-Fi 信息
    func loadWifiInfos() -> [WifiInfo] {
        guard let data = KeychainManager.get(forKey: wifiInfoKey) as? Data else {
            return [] // 无数据时返回空数组
        }
        if let rawString = String(data: data, encoding: .utf8) {
            print("Keychain 读取的原始数据：\(rawString)")
            
            guard let trimmed = String(data: data, encoding: .utf8)?
                .replacingOccurrences(of: "\\", with: "")
                .trimmingCharacters(in: CharacterSet(charactersIn: "\"")) else { return [] }
            
            guard let decodedData = Data(base64Encoded: trimmed) else {
                print("Base64 解码失败：字符串格式无效")
                return []
            }
            if let jsonString = String(data: decodedData, encoding: .utf8) {
                print("解码后的 JSON 字符串:", jsonString)
            }
            
            do {
                return try JSONDecoder().decode([WifiInfo].self, from: decodedData)
            } catch {
                print("解码失败: \(error)")
                // 兼容旧格式（如之前存的是字符串）
                if let legacyString = String(data: data, encoding: .utf8) {
                    print("警告：检测到旧格式数据，建议迁移: \(legacyString)")
                }
                return []
            }
        }
        return []
    }
    
    // MARK: - 清空 Keychain 中的 Wi-Fi 数据
    func eraseAllWifiInfo() -> Bool {
        return KeychainManager.erase(key: wifiInfoKey)
    }
}
